﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Monitor.Filters;
using Monitor.Models.ForWorkWithRepository;
using Monitor.Models.Json;
using ServiceStack.Text;

namespace Monitor.Controllers.ApiControllers.Administrator
{

    public class ClassificatorController : MainApiController
    {
        #region GET
        [WebApiOutputCache(3000, 300, true)]
        public IEnumerable<JsonItem> Get()
        {
            return Get(null);
        }

        // GET api/classificator
        [WebApiOutputCache(3000, 300,true)]
        public IEnumerable<JsonItem> Get(Int64? id)
        {
            try
            {
                return DataRepository
                    .ClassificatorRepository
                    .GetBranchTree(id)
                    .OrderBy(n => n.FullName)
                    .Select(n => new JsonItem()
                                     {
                                         id = n.Id,
                                         label = n.FullName,
                                         value = n.Name,
                                         items = (Math.Ceiling(n.Id / 10000000.0) == n.Id / 10000000.0)//учет специфики классификатора
                                                     ? new Item[1]
                                                           {
                                                               new Item()
                                                                   {
                                                                       label = "Loading...",
                                                                       value = n.Id
                                                                   }
                                                           }
                                                     : new Item[0]
                                     });
            }
            catch (Exception e)
            {
                ErrorLogger.Error(string.Format("HomeController - Get id:{0}", id), e);
                return new JsonItem[0];
            } 
        }

       // [WebApiOutputCache(5, 60, true)]
        public IEnumerable<JsonItem> Get(Int64 id, string name_startsWith)
        {
            try
            {
                if (string.IsNullOrEmpty(name_startsWith))
                    return Get(id);
                else
                    return DataRepository
                        .ClassificatorRepository
                        .GetBranchTree(id)
                        .Where(n => n.FullName.Contains(name_startsWith))
                        .OrderBy(n => n.FullName)
                        .Take(10)//первых десять 
                        .Select(n => new JsonItem()
                                         {
                                             id = n.Id,
                                             label = n.FullName,
                                             value = n.Name,
                                             items =
                                                 (Math.Ceiling(n.Id/10000000.0) == n.Id/10000000.0)
                                                 //учет специфики классификатора
                                                     ? new Item[1]
                                                           {
                                                               new Item()
                                                                   {
                                                                       label = "Loading...",
                                                                       value = n.Id
                                                                   }
                                                           }
                                                     : new Item[0]
                                         });
            }
            catch (Exception e)
            {
                ErrorLogger.Error(this.ControllerContext, e);
                return new JsonItem[0];
            }
        }
        #endregion


        // POST api/classificator - добавить новый
        public HttpResponseMessage Post([FromBody]ClassifItem value)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var query= DataRepository.ClassificatorRepository.Add(value);
                    JsonItem newItem = new JsonItem()
                                           {
                                               id = query.Id,
                                               label = query.FullName,
                                               value = query.Name
                                           };
                    return Request.CreateResponse(HttpStatusCode.OK, newItem);
                }
                catch (Exception e)
                {
                    ErrorLogger.Error(this.ControllerContext, e);
                    return Request.CreateResponse(HttpStatusCode.Conflict);
                }
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.Forbidden);
            }
        }

        // PUT api/classificator/ - изменить
        public HttpResponseMessage Put([FromBody]ClassifItem value)
        {
            if (ModelState.IsValid&&value.Id.HasValue)
            {
                try
                {
                    DataRepository.ClassificatorRepository.Update(value);
                    JsonItem newItem = new JsonItem()
                                           {
                                               id = value.Id.Value,
                                               label = value.FullName,
                                               value = value.Name,
                                               items = new Item[1]
                                                     {
                                                         new Item()
                                                             {
                                                                 label = "Loading...",
                                                                 value = value.Id.Value
                                                             }
                                                     }
                                           };
                    return Request.CreateResponse(HttpStatusCode.OK, newItem);
                }
                catch (Exception e)
                {
                    ErrorLogger.Error(this.ControllerContext, e);
                    return Request.CreateResponse(HttpStatusCode.Conflict);
                }
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.Forbidden);
            }
        }

        // DELETE api/classificator/
        public HttpResponseMessage Delete(long id)
        {
            try
            {
                DataRepository.ClassificatorRepository.Delete(id);
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (Exception e)
            {
                ErrorLogger.Error(this.ControllerContext, e);
                return Request.CreateResponse(HttpStatusCode.Forbidden);
            }
        }
    }
}
